import { Injectable } from '@nestjs/common';
import { HEXAGRAMS_DATA } from './hexagrams-data';
import { AiInterpretationService } from './ai-interpretation.service';

export interface Hexagram {
  id: number;
  name: string;
  chineseName: string;
  symbol: string;
  description: string;
  interpretation: string;
  lines: string[];
}

@Injectable()
export class YijingService {
  private readonly hexagrams: Hexagram[] = HEXAGRAMS_DATA;

  constructor(private readonly aiInterpretationService: AiInterpretationService) { }

  // 生成卦象
  generateHexagram(): Hexagram {
    const randomIndex = Math.floor(Math.random() * this.hexagrams.length);
    return this.hexagrams[randomIndex];
  }

  // 通过三枚硬币生成卦象
  generateHexagramByCoins(): Hexagram {
    const lines: number[] = [];

    // 生成六爻
    for (let i = 0; i < 6; i++) {
      const coin1 = Math.random() < 0.5 ? 0 : 1; // 0为阴，1为阳
      const coin2 = Math.random() < 0.5 ? 0 : 1;
      const coin3 = Math.random() < 0.5 ? 0 : 1;

      const sum = coin1 + coin2 + coin3;
      // 0个阳：老阴（变爻）
      // 1个阳：少阳
      // 2个阳：少阴
      // 3个阳：老阳（变爻）
      lines.push(sum);
    }

    // 根据六爻确定卦象
    const hexagramId = this.calculateHexagramId(lines);
    return this.hexagrams[hexagramId - 1] || this.hexagrams[0];
  }

  // 通过数字生成卦象
  generateHexagramByNumber(): Hexagram {
    const randomNumber = Math.floor(Math.random() * 64) + 1;
    return this.hexagrams[randomNumber - 1];
  }

  // 根据六爻计算卦象ID
  private calculateHexagramId(lines: number[]): number {
    // 根据六爻的组合计算对应的64卦ID
    // 0=老阴(变爻), 1=少阳, 2=少阴, 3=老阳(变爻)
    const binaryString = lines.map(line => {
      if (line === 0) return '0'; // 老阴
      if (line === 1) return '1'; // 少阳
      if (line === 2) return '0'; // 少阴
      if (line === 3) return '1'; // 老阳
      return '0';
    }).join('');

    const decimal = parseInt(binaryString, 2);
    return decimal + 1; // 返回1-64的ID
  }

  // 获取所有卦象
  getAllHexagrams(): Hexagram[] {
    return this.hexagrams;
  }

  // 根据ID获取卦象
  getHexagramById(id: number): Hexagram | undefined {
    return this.hexagrams.find(hexagram => hexagram.id === id);
  }

  // 解卦
  async interpretHexagram(hexagram: Hexagram, question?: string): Promise<string> {
    try {
      // 使用AI解读
      return await this.aiInterpretationService.interpretHexagram(hexagram, question);
    } catch (error) {
      console.error('AI解读失败，使用传统解读:', error);
      // 如果AI解读失败，回退到传统解读
      return this.getTraditionalInterpretation(hexagram, question);
    }
  }

  // 传统解卦方法（备用）
  private getTraditionalInterpretation(hexagram: Hexagram, question?: string): string {
    let interpretation = `卦象：${hexagram.chineseName}（${hexagram.name}）\n`;
    interpretation += `象征：${hexagram.description}\n`;
    interpretation += `卦辞：${hexagram.interpretation}\n\n`;

    if (question) {
      interpretation += `针对问题"${question}"的解答：\n`;
    }

    interpretation += `爻辞解读：\n`;
    hexagram.lines.forEach((line, index) => {
      interpretation += `${line}\n`;
    });

    interpretation += `\n总体建议：此卦象提示您需要保持内心的平静，顺应自然规律，以诚待人，方能获得吉祥。`;

    return interpretation;
  }
}
